import { reqCartList, reqDeleteCartById, reqUpdateCheckedByid } from '@/api/index'
const state = {
  cartList: []
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  // 获取购物车列表数据
  async getCartList({ commit }) {
    let result = await reqCartList()
    if (result.code === 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  // 删除购物车某一个产品
  async deleteCartListBySkuId({ commit }, skuId) {
    const result = await reqDeleteCartById(skuId)
    if (result.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改购物车某一个产品的选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    const result = await reqUpdateCheckedByid(skuId, isChecked)
    if (result.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除全部勾选的商品
  deleteAllCheckedCar({ dispatch, getters }) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      if (item.isChecked === 1) {
        let promise = dispatch('deleteCartListBySkuId', item.skuId)
        PromiseAll.push(promise)
      }
    })
    // 最终返回全部都成功了就提示成功，有一个失败了都返回失败
    return Promise.all(PromiseAll)
  }
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },

}

export default {
  state,
  mutations,
  actions,
  getters
}